import React from 'react';
import { Form, Row, Col, Input, Modal, Select, DatePicker, Button,  notification ,Message, Calendar, Pagination } from 'antd';
import CalendarActions from './actions/calendarActions';
import JobAlertModel from './jobAlertModel';

const FormItem = Form.Item;
const Option = Select.Option;

var Reflux = require('reflux');
var ReqDateStore = require('./stores/reqDateStore'); // 已选中时间store

let jobAlert = React.createClass({

  mixins: [
    Reflux.listenTo(ReqDateStore, 'onGetReqDate'),
  ],
  // 获取reflux中onGetReqDate
  onGetReqDate(val) {
    this.setState({
      ReqDate: val,
    });
  },

  getInitialState() {
    return {
      visible: false,
      visible2: false,
      houseData: {},
      data: [],
      ReqDate: '',
      value: new Date(),
      id: '',
      forms: {},
      canEdit: true,
      feedback: '',
      updateList: {},
      detailList: {},
      updateBackList: [],
      calendarList: [] //提醒消息日期
    }
  },

  componentDidMount() {
    var newValue = Utils.formatDate(this.state.value) + " 00:00:00"
    CalendarActions.getReqDate({reqDate: newValue});

    this.fetch();
  },

  // 获取提醒事项数据
  fetch() {
    let newValue ={ReqDate: Utils.formatDate(this.state.value) + " 00:00:00"};
    let _me = this
    Utils.sendAjax({
      url: '/job/remind/calendar',
      data: JSON.stringify(newValue),
      type: 'json',
      callback: function (result) {
        if (result.code == '200') {
          _me.setState({
            data: result.data.remindList,
            calendarList: result.data.calendarList,
            forms: result.data,
          })
          _me.getDataList(result.data.remindList);

        } else {
          Message.error(result.message, 10)
        }
      }
    })
  },

  getDataList(data){
    return data;
  },

  handleSubmit(e){
    e.preventDefault();
    /* console.log('收到x表单值：', this.props.form.getFieldsValue());*/
    let param = this.props.form.getFieldsValue();
    param.remindTime = Utils.formatDate(param.remindTime)
    let _me = this

    this.props.form.validateFields((errors, values) => {
      if (!!errors) {
        /* console.log('Errors in form!!!');*/
        return;
      }

      Utils.sendAjax({
        url: '/job/remind/add',
        data: JSON.stringify(param),
        callback: (result) => {
          if (result.code === '200') {
            this.fetch()

          } else {

            notification.error({message: result.message});
          }
        }
      });
      this.handleOk()
    });

  },

  //点击"设为解决"
  isSolve(id){
    // document.getElementById("solve").style.visibility = "hidden";
    let _me = this;

    Utils.sendAjax({
      url: '/job/remind/update',
      data: JSON.stringify({remindId: id}),
      type: 'json',
      callback: function (result) {
        if (result.code == '200') {
          _me.fetch();
        } else {
          Message.error(result.message, 10)
        }
      }
    });


  },

  //点击日历日期 渲染内容
  onSelect(value){
    console.log(value)
    var fields = value.fields;
    console.log(fields)
    var newValue = `${fields[1]}-${(fields[2] + 1) >= 10 ? (fields[2] + 1) : '0'+ (fields[2] + 1) }-${fields[3] >= 10 ? fields[3] : '0'+fields[3]}` + ' 00:00:00';
    console.log(newValue)
    CalendarActions.getReqDate({reqDate: newValue});
    let _me = this
    Utils.sendAjax({
      url: '/job/remind/calendar',
      data: JSON.stringify({reqDate: newValue}),
      type: 'json',
      callback: function (result) {
        /* console.log(result.data)*/
        if (result.code == '200') {
          _me.setState({
            data: result.data.remindList,
            forms: result.data,
          })
        } else {
          Message.error(result.message, 10)
        }
      }
    })
    this.setState({
      value: new Date(value.time)
    })

  },

  getListData(value) {
    let listData;
    this.state.calendarList.forEach((item)=> {
        let dateArr = item.remindTime.split(' ')[0];
        let oneMount = dateArr.split('-')[1]; //
        let oneDate = dateArr.split('-')[2]; //
        let anyDate = value.getDayOfMonth();
        let anyMonth = value.getMonth() + 1;
        if (oneMount == anyMonth && anyDate == oneDate) {
          if (item.calendarStatus == 1 || item.calendarStatus == 4) {
            listData = [
              {type: 'normal'}
            ];
          } else {
            listData = [
              {type: 'warning'},
            ];
          }
        }
      }
    )
    return listData || [];
  },

  dateCellRender(value) {
    const listData = this.getListData(value);
    return (
      <ul className="events">
        {
          listData.map((item, index) =>
            <li key={index}>
              <span className={`event-${item.type}`}>●</span>
            </li>
          )
        }
      </ul>
    );
  },

  feedUpdate(id) {
    let me = this;
    let forms= this.props.form.getFieldsValue();
    let params=Object.assign({},{remindId: id},forms);
    this.props.form.resetFields();
      Utils.sendAjax({
        url: '/job/remind/findFeedback',
        data: JSON.stringify(params),
        callback: function(result){
          if (result.code == '200') {
            me.setState({
              detailList: result.data,
              visible2:　true,
              canEdit: true

            })
          }else {
            Message.error(result.message, 10);
          }
        }
      })
  },

  //对话框
  showModal() {
    this.setState({
      visible: true,

    })
    this.handleReset();

  },
  showFeedUpdate (id) {
    this.setState({
      visible2: true
    })
    this.feedUpdate(id);

  },
  handleReset() {
    this.props.form.resetFields();
  },

  handleOk() {
    this.setState({
      visible: false,

    });
  },

  handleCancel(e) {
    this.setState({
      visible: false,
   
    });
  },
  
  handleCancelJobAlert() {
    
    this.setState({
      visible2: false
    })
    
  },

  onPanelChange(value, mode) {
    console.log(value, mode);
  },

  render(){

    const { getFieldProps } = this.props.form;
    const forms = this.state.forms;
    let updateList = this.state.updateList ? this.state.updateList : [];
    let dataList = this.state.data ? this.state.data : [];
    let feedValue = this.props.form.getFieldsValue();
    let boxArr = [];
    dataList.forEach((item)=> {
      console.log(item.content.length)
      let statusMap = {
        '1': '已解决',
        '2': '未解决',
        '3': '待付款',
        '4': '已付款'
      }
      let typeMap = {
        '1': '维修',
        '2': '投诉',
        '3': '备忘',
        '4': '自动生成',
        '5': '预约'
      }
      let content = (

        <Form inline key={item.id}>
          {/* <Row gutter={24}>
           <Col sm={8} offset={10}>
           <FormItem>
           <p className="time">{item.remindTime}</p>
           </FormItem>
           </Col>
           </Row>*/}
          <div className="box">
            <Row gutter={24}>
              <Col sm={6}>
                <FormItem >
                  <Button disabled className={`aa ${ item.status == 1 ? 'color11' : 'color22'}`} id="status"
                          type="ghost" size="small">{statusMap[item.status]}</Button>
                </FormItem>
                <FormItem >
                  {item.type!== 4 ? <Button  disabled  id="type" type="ghost" className={` ${ item.status == 1 ? 'color11' : 'color22'}`}
                                            size="small">{typeMap[item.type]}</Button> : null }

                </FormItem>
                <FormItem>
                  {item.type == 1 || item.type == 2 ? <Button type="ghost" size="small" className={` ${ item.status == 1 ? 'color11' : 'color22'}`} onClick={this.showFeedUpdate.bind(this, item.id)}>
                    回馈</Button> : null}
                </FormItem>
              </Col>
              <Col sm={16} className="text-box">
                <FormItem >
                  <div className={`${ item.status == 1 ? 'font-gray' : ''}`}>
                    <p className="ant-form-text" >{item.createTime}</p>
                    <p className="ant-form-text ipt-content" title={item.content}>{item.content}</p>
                    <p className="ant-form-text">{item.ownerName}</p>
                    <p className="ant-form-text">{item.mobilePhone}</p>
                  </div>
                </FormItem>
              </Col>
              { item.status == 2 ?
                <Col sm={16}>
                  <FormItem >
                    <Button id="solve"  className="solve"
                           onClick={this.isSolve.bind(this,item.id)}>设为解决</Button>
                  </FormItem>
                </Col> : ''
              }
            </Row>
          </div>
        </Form>

      )
      boxArr.push(content)
    })
    /* console.log('boxArr', boxArr)*/

    const typeProps = getFieldProps('type', {});

    const remindTimeProps = getFieldProps('remindTime', {
      rules: [
        {required: true,type: 'date', message: '请选择日期'},
      ],
    });
    const contentProps = getFieldProps('content', {
      rules: [
        {required: true, message: '请输入工作内容'},
      ],
    });
    
    console.log(this.state.value);
    return (
      <div>

        <div className="calendar">
          <Calendar fullscreen={false} onSelect={this.onSelect} dateCellRender={this.dateCellRender}
                    />
        </div>
        <div className="remind-box">
            <div className="newRemined">
            <Form inline >
              <Row gutter={24}>
                <Col sm={12}>
                  <FormItem>
                    <a onClick={this.showModal} >添加新提醒</a>
                  </FormItem>
                </Col>
                <Col sm={12}>
                  <FormItem>
                    <p className="time">{forms.remindTime}</p>
                  </FormItem>
                </Col>
              </Row>
            </Form>
              </div>
          <div style={{marginTop: 50}}>
            {boxArr}
          </div>
          <Modal title="添加提醒" footer=""
                 visible={this.state.visible}
                 onOk={this.handleOk} onCancel={this.handleCancel}
          >
            <div className="form-group2">
              <Form inline form={this.props.form}>
                <Row gutter={24}>
                  <Col sm={24}>
                    <FormItem label="类别">
                      <Select {...typeProps} /*{...getFieldProps('type', {initialValue: houseData.type})}*/
                        style={{width: 162}}>
                        <Option value="1">维修</Option>
                        <Option value="2">投诉</Option>
                        <Option value="3">备忘</Option>
                      </Select>
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={24}>
                  <Col sm={24}>
                    <FormItem label="日期">
                      <DatePicker
                        {...remindTimeProps}
                      />
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={24}>
                  <Col sm={24}>
                    <FormItem label="工作内容">
                      <Input type="textarea" className="add-txt"
                             style={{width: 500}} {...contentProps} /*{...getFieldProps('content', {initialValue: houseData.content})}*//>
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={24} style={{margin: 20}}>
                  <Col sm={24} offset={9}>
                    <FormItem label="">
                      <Button type="primary" onClick={this.handleSubmit}>添加提醒</Button>
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </div>
          </Modal>
        </div>
        <JobAlertModel visible={this.state.visible2}
                       detailList={this.state.detailList}
                       handleCancelJobAlert = {this.handleCancelJobAlert}
        />
      </div>
    );
  }
});
jobAlert = Form.create()(jobAlert);
export default jobAlert